package com.yy.studyspringboot.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//filterName为过滤器名字，urlPatterns为过滤的url地址
@WebFilter(filterName = "filterTest", urlPatterns = "/test/filter")
public class FilterTest implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("--------------------->过滤器被创建");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8");//设置字符编码
        response.setCharacterEncoding("UTF-8"); //设置字符编码
        String requestURI = request.getRequestURI();//得到被过滤的请求地址
        //将不需要过滤的请求地址踢出
        if ("/filter/to_login".equals(requestURI)||"/filter/do_login".equals(requestURI)){
        	System.out.println("------- 踢出 ------>过滤器：请求地址" + requestURI);
            filterChain.doFilter(request, response);//放行
            return;
        }
        System.out.println("------- 开始过滤 ------>过滤器：请求地址" + requestURI);
        filterChain.doFilter(request, response);//放行
    }

    @Override
    public void destroy() {
        System.out.println("--------------------->过滤器被销毁");
    }
}

